package middleware

import (
	"github.com/gin-gonic/gin"
	"mine-info-server/global"
	"mine-info-server/utils/jwt_util"
	"mine-info-server/utils/response"
)

// 鉴权解析token
func Token() gin.HandlerFunc {
	return func(c *gin.Context) {
		if "/manage-api/v1/adminUser/login" == c.Request.RequestURI {
			c.Next()
			return
		}
		if "/manage-api/v1/adminUser/loginV2" == c.Request.RequestURI {
			c.Next()
			return
		}
		// 从请求头中拿到token
		token := c.Request.Header.Get("token")
		// 解析鉴权
		claims, err := jwt_util.ParseToken(token)
		if err != nil {
			// 鉴权失败
			global.GVA_LOG.Error("鉴权失败")
			response.NoAuthWithMessage("鉴权失败", c)
			c.Abort()
			return
		}
		// 将user_id塞入context中
		c.Set("user_id", claims.UserId)
		c.Next()
	}
}
